import { Component, toNative } from 'vue-facing-decorator'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { FilterDto } from '@/render/FilterRender'
import type { VxeColumnSlotTypes, VxeGridPropTypes, VxeTableDataRow } from 'vxe-table'
import type { AnyObject } from '@/types'
import { getKeyToEnum, InvoiceTypeCnEnum, InvoiceUploadStatusCnEnum } from '@/const/enum'
import DialogUpload from './components/DialogUpload'
import { exportInvoice, getInvoiceList, uploadInvoice, uploadInvoiceZip } from '@/api/invoice'
import type { InvoiceDto } from '@/api/invoice/types'
import { downloadFile, getCompanyListByName } from '@/utils/util'
import PreviewImageOrPdf from '@/components/preview-media/PreviewImageOrPdf'
import { Button, message, Tooltip, type UploadFile } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
@Component
export class Uploaded extends TableRender {
    showUploadZip = false
    showUpload = false

    uploadFile = null as File | null
    curItem = {} as InvoiceDto

    filterConfig() {
        return {
            salesId: {
                name: '所属业务员',
                element: 'select',
                optionsType: 'sale'
            },
            receiptIds: {
                name: '收款账户',
                element: 'select',
                optionsType: 'receipt'
            },
            applyTime: {
                name: '发票月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            applicationMonth: {
                name: '申请月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            companyName: {
                name: '申请公司名',
                element: 'select',
                remote: true,
                params: {
                    method: async (val: string) => {
                        const res = await getCompanyListByName(val)
                        console.log(33333, res)
                        this.filters.companyName.options = res?.map(i => {
                            return {
                                label: i.label,
                                value: i.label
                            }
                        })
                    }
                }
            },
            type: {
                name: '发票类型',
                element: 'select',
                options: getKeyToEnum(InvoiceTypeCnEnum)
            },
            openDay: {
                name: '开票月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            checkStatus: {
                name: '核对状态',
                element: 'datetime',
                type: 'daterange'
            }
        } as FilterDto
    }

    tableColumnConfigOld = () => [
        {
            field: 'companyName',
            title: '申请公司名',
            width: 200
        },
        {
            field: 'month',
            title: '发票月份'
        },
        {
            field: 'type',
            title: '发票类型',
            formatter: ({row}) => {
                return InvoiceTypeCnEnum[row.type]
            },
        },
        {
            field: 'applyTime',
            title: '申请时间',
            width: 150
        },
        {
            field: 'amount',
            title: '发票金额',
            slots: {
                default: 'price'
            }
        },
        {
            field: 'salesName',
            title: '所属业务员'
        },
        {
            field: 'bankName',
            title: '收款账户',
            width: 200
        },
        {
            field: 'rechargeAmount',
            title: '充值金额',
            slots: {
                default: 'price'
            }
        },
        {
            field: 'checkStatus',
            title: '核对状态',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams<InvoiceDto>) => {
                    return (
                        <>
                            {row.checkStatus === 0 && <div>正常</div>}
                            {row.checkStatus === 1 && (
                                <Tooltip title="异常原因：发票金额不符">
                                    <div class="text-orange cursor-pointer">异常</div>
                                </Tooltip>
                            )}
                            {row.checkStatus === 2 && <div>待核对</div>}
                        </>
                    )
                }
            }
        },
        {
            field: 'uploadTime',
            title: '开票日期',
            width: 150
        },
        {
            field: 'operate',
            title: '操作',
            width: 200,
            fixed: 'right',
            params: {
                buttons: [
                    {
                        type: 'preview',
                        previewProp: 'invoiceUrl'
                    },
                    {
                        text: '上传发票',
                        icon: UploadOutlined,
                        event: (row: InvoiceDto) => {
                            this.onUpload(row)
                        }
                    }
                ]
            },
            slots: {
                default: 'buttons'
            }
        }
    ] as TableRenderColumnTypes<InvoiceDto>

    onUploadZip() {
        this.showUploadZip = true
    }

    onUpload(row: InvoiceDto) {
        this.showUpload = true
        this.curItem = row
    }

    async onExport() {
        const params = this.getFilters()
        params.status = InvoiceUploadStatusCnEnum.已上传
        const res = await exportInvoice(params)
        downloadFile(res)
    }

    async onConfirm(data: { file: UploadFile[]; close: () => void }, type: string) {
        if (!data.file?.length) {
            message.warning('请先上传文件')
            return
        }
        const fileData = new FormData()
        fileData.append('file', data.file[0].originFileObj as File)
        if(type === 'zip') {
            await uploadInvoiceZip(fileData)
        } else {
            await uploadInvoice(fileData, this.curItem.id)
        }
        message.success('上传成功')
        this.reloadPage()
        data.close()
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        return getInvoiceList({
            pageNum: page,
            pageSize: size,
            status: InvoiceUploadStatusCnEnum.已上传,
            ...filters
        })
    }

    renderRightBtns() {
        return (
            <div class="flex gap-20px">
                <Button icon={h(UploadOutlined)} onClick={this.onUploadZip}>
                    上传
                </Button>
                <Button icon={h(UploadOutlined)} onClick={this.onExport}>
                    导出
                </Button>
            </div>
        )
    }

    render() {
        return (
            <>
                {super.render()}
                <DialogUpload
                    v-model:show={this.showUploadZip}
                    onConfirm={(event) => this.onConfirm(event, 'zip')}
                    accept=".zip"
                    v-slots={{
                        default: () => {
                            return (
                                <div class="text-red">
                                    <div>
                                        批量上传电子签发票文件名格式：电子签__年-月.zip；如：电子签__2022-01.zip
                                    </div>
                                    <div>
                                        批量上传日日保发票文件名格式：日日保__年-月.zip；如：日日保__2022-01.zip
                                    </div>
                                </div>
                            )
                        }
                    }}
                />

                <DialogUpload v-model:show={this.showUpload} onConfirm={(event) => this.onConfirm(event, 'single')} />
            </>
        )
    }
}

export default toNative(Uploaded)
